package com.visionblue.business.ship.page.register.register

import android.app.Activity
import android.os.Bundle
import com.visionblue.business.ship.R
import com.visionblue.business.ship.base.BaseVMFragment
import com.visionblue.business.ship.base.DefaultObserver
import com.visionblue.business.ship.page.dialog.LoadingDialog
import com.visionblue.business.ship.page.dialog.RegisterQuitDialog
import com.visionblue.business.ship.util.ext.showText
import com.visionblue.business.ship.util.toast
import kotlinx.android.synthetic.main.frag_register.*
import org.koin.androidx.viewmodel.ext.android.getViewModel

/**
 * @author: xlh
 * @date: 2020-07-21 4:32 PM
 * @desc:
 */
class RegisterFragment : BaseVMFragment<RegisterViewModel>() {

    private val mDialog: LoadingDialog by lazy {
        LoadingDialog(context!!)
    }

    override fun provideVM(): RegisterViewModel = getViewModel()

    override val layoutId = R.layout.frag_register

    override fun initView(savedInstanceState: Bundle?) {
        tvRegister.setOnClickListener {
            validatePinAndSnCode()
        }
    }

    override fun initData() {
        super.initData()

        mViewModel.validateEvent.observe(this, DefaultObserver {

            if (it.isLoading) {
                mDialog.show()
            } else {
                mDialog.dismiss()
            }

            if (it.isSuccess) {
                toast { "注册成功" }
                activity?.setResult(Activity.RESULT_OK)
                activity?.finish()
            }
        })

        val snAndPinCode = mViewModel.getSnAndPinCode()
        val snCode = snAndPinCode.first
        val pinCode = snAndPinCode.second
        if (snCode.isNotEmpty()) {
            etSn.showText(snCode)
            etPin.showText(pinCode)
        }
    }

    fun onBackClick() {
        if (mViewModel.isEdit(etPin.text.toString().trim(), etSn.text.toString().trim())) {
            showQuitDialog()
        } else {
            activity?.finish()
        }
    }

    private fun validatePinAndSnCode() {
        mViewModel.validatePinAndSnCode(
            etPin.text.toString().trim(),
            etSn.text.toString().trim()
        )
    }

    private fun showQuitDialog() {
        RegisterQuitDialog(context!!).apply {
            onDialogClickListener = object : RegisterQuitDialog.OnDialogClickListener {
                override fun onSaveClick() {
                    validatePinAndSnCode()
                }

                override fun onNotSaveClick() {
                    activity?.finish()
                }
            }
            show()
        }
    }

    companion object{
        fun newInstance(): RegisterFragment {
            return RegisterFragment()
        }
    }

}